package com.yinbao.testservice;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.yinbao.testservice.inter.ServiceAidl;

import java.lang.ref.WeakReference;

/**
 * service测试
 * Created by xing on 2016/11/1.
 */
public class MyService extends Service {

    private static String TAG = "MyService";
    private MyBinder mBinder;
    private MyServiceConn conn;
    private String data;
    private NotificationManager mNotificationManager;
    protected Handler mHandler = new MyHandler(this);

    /**
     * handler消息
     */
    private static class MyHandler extends Handler {
        private WeakReference<MyService> mActivity;

        public MyHandler(MyService mService) {
            mActivity = new WeakReference<>(mService);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mActivity.get() == null) {
                return;
            }
            mActivity.get().uiHandlerMessage(msg);
        }
    }


    /**
     * handler消息处理
     *
     * @param msg
     */
    protected void uiHandlerMessage(Message msg) {
        switch (msg.what) {
            case 1:
                setUpNotification();
                mHandler.sendEmptyMessageDelayed(1, 10000);
                startActivity();

                break;
            case 2:

                break;
        }
    }


    /**
     * 它与bindService()对应，通过返回IBinder，来与service交流。如果你并不像绑定它，就直接返回null
     *
     * @param intent
     * @return
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind事件:它与bindService()对应，通过返回IBinder");
        return mBinder;
    }


    /**
     * 当服务被创建时调用，只调用一次
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate事件:当服务被创建时调用，只调用一次");
        mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        if (mBinder == null) {
            mBinder = new MyBinder();
        }
        conn = new MyServiceConn();

    }

    /**
     * 它与startService()对应，当服务启动后调用。如果你重写了该方法，你就有责任自己去
     * 当任务结束以后，调用stopSelf()或者stopService()来停止服务。如果你是绑定的服务，就不需重新该方法了
     * 服务被启动
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand事件:它与startService()对应，当服务启动后调用");
        //连接MyService
        this.bindService(new Intent(this, YouService.class), conn, BIND_IMPORTANT);//BIND_IMPORTANT提高优先级
        //        Notification notification=new Notification(R.mipmap.ic_launcher,"正在运行",System.currentTimeMillis());
        test1(startId);
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessageDelayed(1, 1000);
            }
        }).start();
        return START_STICKY;//服务就会在资源紧张的时候被杀掉，然后在资源足够的时候再恢复
    }


    /**
     * 创建通知
     */
    private void setUpNotification() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplication());
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setContentTitle("提示");
        mBuilder.setContentText("正在下载");
        mBuilder.setWhen(System.currentTimeMillis());
        mBuilder.setDefaults(Notification.DEFAULT_ALL);
        mBuilder.setAutoCancel(true);
        Intent intent = new Intent(this, TestActivity.class);

        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent
                .FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(0x55, mBuilder.build());
    }


    private void startActivity(){
        Intent mIntent = new Intent(this, TestActivity.class);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        getApplication().startActivity(mIntent);
    }

    private void test1(int startId) {
        Notification notification = new Notification();
        notification.tickerText = "正在运行";//通知显示的文字
        notification.flags = BIND_IMPORTANT;//特性
        startForeground(startId, notification);
        stopForeground(true);
    }


    /**
     * 当服务不再被使用时需要销毁时调用，你应该在这里用来停止线程，注销监听器，广播
     */
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.e(TAG, "onDestroy事件:当服务不再被使用时需要销毁时调用");
        unbindService(conn);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.e(TAG, "onConfigurationChanged事件");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Log.e(TAG, "onLowMemory事件");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        //进行自身的内存释放

        Log.e(TAG, "onTrimMemory事件");
    }

    /**
     * 解除绑定
     *
     * @param intent
     * @return
     */
    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind事件");

        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.e(TAG, "onRebind事件");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.e(TAG, "onTaskRemoved事件");
    }


    private class MyBinder extends ServiceAidl.Stub {
        @Override
        public void getName() throws RemoteException {
            Log.e(TAG, "aidl消息");
        }
    }


    /**
     *
     */
    public class MyBinders extends Binder {
        MyService getService() {
            return MyService.this;
        }

        public void setData(String data) {
            MyService.this.data = data;
        }
    }

    /**
     * 服务连接交互
     */
    private class MyServiceConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            Log.e(TAG, "连接You服务成功");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "断开You服务成功");
            //表示you服务给杀死，重新启动
            MyService.this.startService(new Intent(MyService.this, YouService.class));
            MyService.this.bindService(new Intent(MyService.this, YouService.class), conn, BIND_IMPORTANT);
        }
    }

}
